import { mapState, mapMutations } from 'vuex'
export default {
    data() {
        return {
            currentTab: 'setting',
            isCenterActive: false,
            notificationEnabled: true,
            userName: '', // 初始化为空字符串
            thresholds: {
                temperature: { high: 30, low: 16 },
                humidity: { high: 70, low: 30 },
                airQuality: { high: 75, low: 35 },
                light: { high: 800, low: 200 },
                smoke: { warning: 50 }
            },
            thresholdOptions: {
                temperature: {
                    low: [10, 12, 14, 16, 18, 20],
                    high: [25, 28, 30, 32, 35, 38]
                },
                humidity: {
                    low: [20, 25, 30, 35, 40],
                    high: [60, 65, 70, 75, 80]
                },
                airQuality: {
                    low: [30, 35, 40, 45, 50],
                    high: [70, 75, 80, 85, 90]
                },
                light: {
                    low: [100, 150, 200, 250, 300],
                    high: [600, 700, 800, 1000, 3000]
                },
                smoke: {
                    warning: [30, 40, 50, 60, 70]
                }
            }
        }
    },
    computed: {

    },
    methods: {
        // 切换标签页
        switchTab(tab) {
            this.currentTab = tab;
            switch(tab) {
                case 'home':
                    uni.redirectTo({
                        url: '/pages/index/index',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'notify':
                    uni.redirectTo({
                        url: '/pages/notify/notify',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'control':
                    uni.redirectTo({
                        url: '/pages/control/control',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
            }
        },
        // 获取图标路径
        getTabIcon(tab) {
            const baseUrl = '../../static/';
            return this.currentTab === tab ?
                `${baseUrl}${tab}-active.png` :
                `${baseUrl}${tab}.png`;
        },
        // 处理中间按钮点击
        handleCenterClick() {
            this.isCenterActive = !this.isCenterActive;
            // 添加页面跳转
            uni.redirectTo({
                url: '/pages/deepseek/deepseek',
                animationType: 'pop-in',
                animationDuration: 200
            });
        },
        // 打开阈值设置弹窗
        openThresholdSetting(type) {
            switch(type) {
                case '温度':
                    uni.showActionSheet({
                        itemList: ['设置最低温度', '设置最高温度'],
                        success: (res) => {
                            if(res.tapIndex === 0) {
                                this.showThresholdPicker('temperature', 'low', '最低温度');
                            } else {
                                this.showThresholdPicker('temperature', 'high', '最高温度');
                            }
                        }
                    });
                    break;

                case '湿度':
                    uni.showActionSheet({
                        itemList: ['设置最低湿度', '设置最高湿度'],
                        success: (res) => {
                            if(res.tapIndex === 0) {
                                this.showThresholdPicker('humidity', 'low', '最低湿度');
                            } else {
                                this.showThresholdPicker('humidity', 'high', '最高湿度');
                            }
                        }
                    });
                    break;

                case '空气质量':
                    uni.showActionSheet({
                        itemList: ['设置最低空气质量', '设置最高空气质量'],
                        success: (res) => {
                            if(res.tapIndex === 0) {
                                this.showThresholdPicker('airQuality', 'low', '最低空气质量阈值');
                            } else {
                                this.showThresholdPicker('airQuality', 'high', '最高空气质量阈值');
                            }
                        }
                    });
                    break;

                case '烟雾浓度':
                    this.showThresholdPicker('smoke', 'warning', '警戒值');
                    break;

                case '光照强度':
                    uni.showActionSheet({
                        itemList: ['设置最低光照', '设置最高光照'],
                        success: (res) => {
                            if(res.tapIndex === 0) {
                                this.showThresholdPicker('light', 'low', '最低光照');
                            } else {
                                this.showThresholdPicker('light', 'high', '最高光照');
                            }
                        }
                    });
                    break;
            }
        },

        // 显示阈值选择器
        showThresholdPicker(type, level, title) {
            const options = this.thresholdOptions[type][level].map(String);
            uni.showActionSheet({
                itemList: options,
                title: `请选择${title}`,
                success: (res) => {
                    const value = Number(options[res.tapIndex]);
                    // 获取存储的阈值
                    const savedThresholds = uni.getStorageSync('thresholds');
                    let currentThresholds = this.thresholds;
                    // 确保所有必要的属性都存在
                    if (savedThresholds) {
                        const parsedThresholds = JSON.parse(savedThresholds);
                        currentThresholds = {
                            temperature: parsedThresholds.temperature || { high: 30, low: 16 },
                            humidity: parsedThresholds.humidity || { high: 70, low: 30 },
                            airQuality: parsedThresholds.airQuality || { high: 75, low: 35 },
                            light: parsedThresholds.light || { high: 800, low: 200 },
                            smoke: parsedThresholds.smoke || { warning: 50 }
                        };
                    }

                    if(level === 'warning') {
                        currentThresholds[type][level] = value;
                    } else {
                        // 检查最高值和最低值的合理性
                        const otherLevel = level === 'low' ? 'high' : 'low';
                        // 确保当前类型的阈值对象存在
                        if (!currentThresholds[type]) {
                            currentThresholds[type] = { high: 75, low: 35 }; // 默认值
                        }

                        if((level === 'low' && value >= currentThresholds[type][otherLevel]) ||
                            (level === 'high' && value <= currentThresholds[type][otherLevel])) {
                            uni.showToast({
                                title: '设置值不合理',
                                icon: 'none'
                            });
                            return;
                        } else {
                            currentThresholds[type][level] = value;
                        }
                    }

                    this.thresholds = currentThresholds;
                    this.saveThresholds();
                }
            });
        },

        // 保存阈值设置
        saveThresholds() {
            uni.setStorageSync('thresholds', JSON.stringify(this.thresholds));
            uni.$emit('thresholdsUpdated');
            uni.showToast({
                title: '设置已保存',
                icon: 'success'
            });
        },

        // 获取阈值显示文本
        getThresholdText(type) {
            if (!this.thresholds) return '';

            switch(type) {
                case '温度':
                    if (!this.thresholds.temperature) return '';
                    return `${this.thresholds.temperature.low}°C ~ ${this.thresholds.temperature.high}°C`;
                case '湿度':
                    if (!this.thresholds.humidity) return '';
                    return `${this.thresholds.humidity.low}% ~ ${this.thresholds.humidity.high}%`;
                case '空气质量':
                    if (!this.thresholds.airQuality) return '';
                    return `${this.thresholds.airQuality.low}mg/m³ ~ ${this.thresholds.airQuality.high}mg/m³`;
                case '烟雾浓度':
                    if (!this.thresholds.smoke) return '';
                    return `${this.thresholds.smoke.warning}mg/m³`;
                case '光照强度':
                    if (!this.thresholds.light) return '';
                    return `${this.thresholds.light.low}lux ~ ${this.thresholds.light.high}lux`;
                default:
                    return '';
            }
        },

        // 添加通知开关处理方法
        toggleNotification() {
            this.notificationEnabled = !this.notificationEnabled;
            uni.setStorageSync('notificationEnabled', this.notificationEnabled);

            // 发送通知状态更新事件
            uni.$emit('notificationStatusChanged', this.notificationEnabled);

            // 显示提示
            // uni.showToast({
            //     title: this.notificationEnabled ? '已开启通知' : '已关闭通知',
            //     icon: 'none'
            // });
        },
        goToFurniture() {
            uni.navigateTo({
                url: '/pages/furniture/furniture'
            });
        },
        //点击跳转
        handleCardClick(cardInfo, event) {
            uni.navigateTo({
                url: '/pages/power/power'
            });
        },
        // 修改用户名 - 通过接口更新
        changeUserName() {
            uni.showModal({
                title: '更换用户名',
                editable: true,
                placeholderText: '输入新名字',
                success: (res) => {
                    if (res.confirm && res.content) {
                        // 通过接口更新用户名
                        uni.request({
                            url: 'http://127.0.0.1:7878/user',
                            method: 'PUT',
                            data: {
                                id: 1, // 假设用户ID为1
                                name: res.content
                            },
                            header: {
                                'content-type': 'application/json'
                            },
                            success: (response) => {
                                if (response.data.code === 200 && response.data.data === true) {
                                    // 更新成功，重新获取用户名
                                    this.fetchUserName();
                                    uni.showToast({
                                        title: '用户名已更新',
                                        icon: 'success'
                                    });
                                } else {
                                    uni.showToast({
                                        title: '更新失败',
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: () => {
                                uni.showToast({
                                    title: '网络请求失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                }
            });
        },
        // 从后端获取用户名
        fetchUserName() {
            uni.request({
                url: 'http://127.0.0.1:7878/user',
                method: 'GET',
                success: (res) => {
                    if (res.data.code === 200 && res.data.data) {
                        this.userName = res.data.data.name;
                    } else {
                        console.error('获取用户名失败:', res.data.msg);
                    }
                },
                fail: (err) => {
                    console.error('获取用户名请求失败:', err);
                    uni.showToast({
                        title: '获取用户信息失败',
                        icon: 'none'
                    });
                }
            });
        }
    },
    // 修改生命周期钩子
    onLoad() {
        try {
            // 加载保存的阈值设置
            const savedThresholds = uni.getStorageSync('thresholds');
            if (savedThresholds) {
                const parsedThresholds = JSON.parse(savedThresholds);
                // 确保所有必要的属性都存在
                this.thresholds = {
                    temperature: parsedThresholds.temperature || { high: 30, low: 16 },
                    humidity: parsedThresholds.humidity || { high: 70, low: 30 },
                    airQuality: parsedThresholds.airQuality || { high: 75, low: 35 },
                    light: parsedThresholds.light || { high: 800, low: 200 },
                    smoke: parsedThresholds.smoke || { warning: 50 }
                };
            }

            // 加载通知设置状态
            const notificationStatus = uni.getStorageSync('notificationEnabled');
            if (notificationStatus !== '') {
                this.notificationEnabled = notificationStatus;
            }
            // 从后端获取用户名
            this.fetchUserName();
        } catch (error) {
            console.error('加载设置失败:', error);
            // 使用默认值
            this.thresholds = {
                temperature: { high: 30, low: 16 },
                humidity: { high: 70, low: 30 },
                airQuality: { high: 75, low: 35 },
                light: { high: 800, low: 200 },
                smoke: { warning: 50 }
            };
        }
    },
    // 页面显示时刷新用户名
    onShow() {
        // 每次显示页面时重新获取用户名
        this.fetchUserName();
    }
}